package cn.tedu.charging.device.dao.repository;

import cn.tedu.charging.common.pojo.po.ChargingGunInfoPO;
import cn.tedu.charging.device.dao.mapper.ChargingGunInfoMapper;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
@Slf4j
public class GunRepository {
    @Autowired
    private ChargingGunInfoMapper chargingGunInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public List<ChargingGunInfoPO> getGunsByStationId(Integer stationId) {
        String key="station:guns:cache"+stationId;
        ListOperations<String, ChargingGunInfoPO> ops=redisTemplate.opsForList();
        List<ChargingGunInfoPO> guns=ops.range(key,0,-1);
        if (CollectionUtils.isNotEmpty(guns)){
            log.info("从缓存中获取数据");
            return guns;
        }
        log.info("从数据库中获取数据");
        guns=chargingGunInfoMapper.selectGunsByStationId(stationId);
        if (CollectionUtils.isNotEmpty(guns)){
            ops.leftPushAll(key,guns);
        }
        return guns;
    }

    public int countByIdAndStatus(Integer gunId, int i) {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("id",gunId);
        queryWrapper.eq("gun_status",i);
        return chargingGunInfoMapper.selectCount(queryWrapper).intValue();
    }
}
